using System;
using System.Collections.Generic;
using UnityEngine;
using GenerativeAgents.Core;

namespace GenerativeAgents.Unity
{
    /// <summary>
    /// 环境对象
    /// 表示环境中可以与智能体交互的物体
    /// </summary>
    public class EnvironmentObject : MonoBehaviour
    {
        [Header("对象属性")]
        [SerializeField] private string objectName = "Object";
        [SerializeField] private ObjectType objectType = ObjectType.Static;
        [SerializeField] private string description = "An environment object";
        [SerializeField] private bool isInteractable = true;
        [SerializeField] private float interactionRange = 2f;
        
        [Header("对象状态")]
        [SerializeField] private ObjectState currentState = ObjectState.Idle;
        [SerializeField] private List<string> availableActions;
        [SerializeField] private Dictionary<string, object> properties;
        
        [Header("视觉设置")]
        [SerializeField] private Renderer objectRenderer;
        [SerializeField] private Material[] stateMaterials;
        [SerializeField] private Color[] stateColors;
        
        // 内部状态
        private EnvironmentManager environmentManager;
        private DateTime lastInteractionTime;
        private DateTime lastStateChange;
        private List<AgentController> nearbyAgents;
        
        // 事件
        public event System.Action<EnvironmentObject, AgentController> OnInteraction;
        public event System.Action<EnvironmentObject, ObjectState> OnStateChanged;
        
        public string ObjectName => objectName;
        public ObjectType Type => objectType;
        public string Description => description;
        public ObjectState CurrentState => currentState;
        public bool IsInteractable => isInteractable;
        
        private void Awake()
        {
            InitializeObject();
        }
        
        private void Start()
        {
            RegisterWithEnvironment();
        }
        
        private void Update()
        {
            UpdateObject();
        }
        
        /// <summary>
        /// 初始化对象
        /// </summary>
        private void InitializeObject()
        {
            // 初始化数据结构
            availableActions = availableActions ?? new List<string>();
            properties = properties ?? new Dictionary<string, object>();
            nearbyAgents = new List<AgentController>();
            
            // 获取渲染器
            if (objectRenderer == null)
            {
                objectRenderer = GetComponent<Renderer>();
            }
            
            // 设置默认行动
            SetupDefaultActions();
            
            // 初始化时间戳
            lastInteractionTime = DateTime.Now;
            lastStateChange = DateTime.Now;
            
            // 更新视觉表示
            UpdateVisualRepresentation();
        }
        
        /// <summary>
        /// 设置默认行动
        /// </summary>
        private void SetupDefaultActions()
        {
            if (availableActions.Count == 0)
            {
                switch (objectType)
                {
                    case ObjectType.Furniture:
                        availableActions.AddRange(new[] { "sit", "use", "examine" });
                        break;
                        
                    case ObjectType.Tool:
                        availableActions.AddRange(new[] { "use", "pickup", "examine" });
                        break;
                        
                    case ObjectType.Decoration:
                        availableActions.AddRange(new[] { "examine", "admire" });
                        break;
                        
                    case ObjectType.Interactive:
                        availableActions.AddRange(new[] { "interact", "use", "examine" });
                        break;
                        
                    case ObjectType.Container:
                        availableActions.AddRange(new[] { "open", "close", "examine" });
                        break;
                        
                    default:
                        availableActions.AddRange(new[] { "examine" });
                        break;
                }
            }
        }
        
        /// <summary>
        /// 向环境管理器注册
        /// </summary>
        private void RegisterWithEnvironment()
        {
            environmentManager = FindObjectOfType<EnvironmentManager>();
            if (environmentManager != null)
            {
                environmentManager.RegisterEnvironmentObject(this);
            }
        }
        
        /// <summary>
        /// 更新对象
        /// </summary>
        private void UpdateObject()
        {
            try
            {
                // 检测附近的智能体
                DetectNearbyAgents();
                
                // 更新对象状态
                UpdateObjectState();
                
                // 处理自动行为
                ProcessAutomaticBehavior();
            }
            catch (Exception ex)
            {
                Debug.LogError($"[EnvironmentObject] Error updating object '{objectName}': {ex.Message}");
            }
        }
        
        /// <summary>
        /// 检测附近的智能体
        /// </summary>
        private void DetectNearbyAgents()
        {
            nearbyAgents.Clear();
            
            if (environmentManager != null)
            {
                var agents = environmentManager.GetRegisteredAgents();
                foreach (var agent in agents)
                {
                    if (agent != null)
                    {
                        var distance = Vector3.Distance(transform.position, agent.transform.position);
                        if (distance <= interactionRange)
                        {
                            nearbyAgents.Add(agent);
                        }
                    }
                }
            }
        }
        
        /// <summary>
        /// 更新对象状态
        /// </summary>
        private void UpdateObjectState()
        {
            var previousState = currentState;
            
            // 基于环境和交互更新状态
            if (nearbyAgents.Count > 0)
            {
                if (currentState == ObjectState.Idle)
                {
                    ChangeState(ObjectState.Aware);
                }
            }
            else
            {
                if (currentState == ObjectState.Aware && 
                    (DateTime.Now - lastInteractionTime).TotalSeconds > 10)
                {
                    ChangeState(ObjectState.Idle);
                }
            }
            
            // 处理交互状态自动恢复
            if (currentState == ObjectState.InUse && 
                (DateTime.Now - lastInteractionTime).TotalSeconds > 30)
            {
                ChangeState(ObjectState.Idle);
            }
        }
        
        /// <summary>
        /// 处理自动行为
        /// </summary>
        private void ProcessAutomaticBehavior()
        {
            // 根据对象类型执行自动行为
            switch (objectType)
            {
                case ObjectType.Animated:
                    ProcessAnimatedBehavior();
                    break;
                    
                case ObjectType.Interactive:
                    ProcessInteractiveBehavior();
                    break;
            }
        }
        
        /// <summary>
        /// 处理动画对象行为
        /// </summary>
        private void ProcessAnimatedBehavior()
        {
            // 简单的动画循环
            if ((DateTime.Now - lastStateChange).TotalSeconds > 5)
            {
                var newState = currentState == ObjectState.Active ? ObjectState.Idle : ObjectState.Active;
                ChangeState(newState);
            }
        }
        
        /// <summary>
        /// 处理交互对象行为
        /// </summary>
        private void ProcessInteractiveBehavior()
        {
            // 检查是否有智能体尝试交互
            foreach (var agent in nearbyAgents)
            {
                var agentState = agent.GetAgentState();
                if (agentState != null && agentState.currentAction == "interacting")
                {
                    TryInteractWithAgent(agent);
                }
            }
        }
        
        /// <summary>
        /// 尝试与智能体交互
        /// </summary>
        private bool TryInteractWithAgent(AgentController agent)
        {
            if (!isInteractable || currentState == ObjectState.InUse)
            {
                return false;
            }
            
            try
            {
                // 执行交互
                PerformInteraction(agent);
                return true;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[EnvironmentObject] Error during interaction: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 执行交互
        /// </summary>
        private void PerformInteraction(AgentController agent)
        {
            // 更新状态
            ChangeState(ObjectState.InUse);
            lastInteractionTime = DateTime.Now;
            
            // 生成交互事件
            var interactionEvent = AgentEvent.CreateInteractionEvent(
                agent.GetAgentState()?.agentName ?? agent.name,
                objectName,
                "interact",
                transform.position,
                environmentManager?.GetLocationName(transform.position) ?? "unknown"
            );
            
            // 触发事件
            OnInteraction?.Invoke(this, agent);
            
            // 添加到智能体的感知系统
            var perceptionSystem = agent.GetComponent<PerceptionSystem>();
            if (perceptionSystem != null)
            {
                // 这里需要一个方法来直接添加事件到感知系统
                // perceptionSystem.AddDirectEvent(interactionEvent);
            }
            
            Debug.Log($"[EnvironmentObject] {objectName} interacted with {agent.name}");
        }
        
        /// <summary>
        /// 改变状态
        /// </summary>
        private void ChangeState(ObjectState newState)
        {
            if (currentState != newState)
            {
                var previousState = currentState;
                currentState = newState;
                lastStateChange = DateTime.Now;
                
                // 更新视觉表示
                UpdateVisualRepresentation();
                
                // 触发事件
                OnStateChanged?.Invoke(this, newState);
                
                Debug.Log($"[EnvironmentObject] {objectName} state changed from {previousState} to {newState}");
            }
        }
        
        /// <summary>
        /// 更新视觉表示
        /// </summary>
        public void UpdateVisualRepresentation()
        {
            if (objectRenderer == null) return;
            
            try
            {
                // 更新材质
                if (stateMaterials != null && stateMaterials.Length > 0)
                {
                    int materialIndex = (int)currentState % stateMaterials.Length;
                    if (materialIndex < stateMaterials.Length && stateMaterials[materialIndex] != null)
                    {
                        objectRenderer.material = stateMaterials[materialIndex];
                    }
                }
                
                // 更新颜色
                if (stateColors != null && stateColors.Length > 0)
                {
                    int colorIndex = (int)currentState % stateColors.Length;
                    if (colorIndex < stateColors.Length)
                    {
                        objectRenderer.material.color = stateColors[colorIndex];
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[EnvironmentObject] Error updating visual representation: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 手动交互
        /// </summary>
        public bool Interact(AgentController agent, string action = "use")
        {
            if (!isInteractable) return false;
            
            if (availableActions.Contains(action))
            {
                return TryInteractWithAgent(agent);
            }
            
            return false;
        }
        
        /// <summary>
        /// 设置属性
        /// </summary>
        public void SetProperty(string key, object value)
        {
            properties[key] = value;
        }
        
        /// <summary>
        /// 获取属性
        /// </summary>
        public T GetProperty<T>(string key, T defaultValue = default(T))
        {
            if (properties.TryGetValue(key, out var value) && value is T)
            {
                return (T)value;
            }
            return defaultValue;
        }
        
        /// <summary>
        /// 添加可用行动
        /// </summary>
        public void AddAvailableAction(string action)
        {
            if (!availableActions.Contains(action))
            {
                availableActions.Add(action);
            }
        }
        
        /// <summary>
        /// 移除可用行动
        /// </summary>
        public void RemoveAvailableAction(string action)
        {
            availableActions.Remove(action);
        }
        
        /// <summary>
        /// 获取可用行动列表
        /// </summary>
        public List<string> GetAvailableActions()
        {
            return new List<string>(availableActions);
        }
        
        /// <summary>
        /// 设置交互性
        /// </summary>
        public void SetInteractable(bool interactable)
        {
            isInteractable = interactable;
        }
        
        /// <summary>
        /// 获取附近智能体
        /// </summary>
        public List<AgentController> GetNearbyAgents()
        {
            return new List<AgentController>(nearbyAgents);
        }
        
        /// <summary>
        /// 重置对象状态
        /// </summary>
        public void ResetObject()
        {
            ChangeState(ObjectState.Idle);
            lastInteractionTime = DateTime.Now;
            lastStateChange = DateTime.Now;
            nearbyAgents.Clear();
        }
        
        /// <summary>
        /// 获取对象信息
        /// </summary>
        public string GetObjectInfo()
        {
            var info = $"Object: {objectName}\n";
            info += $"Type: {objectType}\n";
            info += $"State: {currentState}\n";
            info += $"Interactable: {isInteractable}\n";
            info += $"Nearby Agents: {nearbyAgents.Count}\n";
            info += $"Available Actions: {string.Join(", ", availableActions)}\n";
            
            return info;
        }
        
        private void OnDestroy()
        {
            // 从环境管理器取消注册
            if (environmentManager != null)
            {
                environmentManager.UnregisterEnvironmentObject(this);
            }
        }
        
        /// <summary>
        /// 绘制调试信息
        /// </summary>
        private void OnDrawGizmosSelected()
        {
            // 绘制交互范围
            Gizmos.color = isInteractable ? Color.green : Color.red;
            Gizmos.DrawWireSphere(transform.position, interactionRange);
            
            // 绘制状态指示器
            Vector3 stateIndicatorPos = transform.position + Vector3.up * 2f;
            switch (currentState)
            {
                case ObjectState.Idle:
                    Gizmos.color = Color.gray;
                    break;
                case ObjectState.Aware:
                    Gizmos.color = Color.yellow;
                    break;
                case ObjectState.Active:
                    Gizmos.color = Color.green;
                    break;
                case ObjectState.InUse:
                    Gizmos.color = Color.red;
                    break;
            }
            Gizmos.DrawSphere(stateIndicatorPos, 0.2f);
        }
    }
    
    /// <summary>
    /// 对象类型枚举
    /// </summary>
    public enum ObjectType
    {
        Static,         // 静态对象
        Furniture,      // 家具
        Tool,          // 工具
        Decoration,    // 装饰品
        Interactive,   // 交互对象
        Container,     // 容器
        Animated,      // 动画对象
        Vehicle        // 载具
    }
    
    /// <summary>
    /// 对象状态枚举
    /// </summary>
    public enum ObjectState
    {
        Idle,          // 空闲
        Aware,         // 感知到智能体
        Active,        // 活跃
        InUse,         // 使用中
        Broken,        // 损坏
        Maintenance    // 维护中
    }
}